﻿// Copyright © Microsoft Corporation.  All Rights Reserved.
// This code released under the terms of the 
// Microsoft Public License (MS-PL, http://opensource.org/licenses/ms-pl.html.)

using System.Windows;
using System.Windows.Interactivity;

namespace Microsoft.Samples
{
    public class CloseAppBehavior : TargetedTriggerAction<FrameworkElement>
    {
        
        protected override void OnAttached()
        {
            // Works only out-of-browser
            if (Application.Current.IsRunningOutOfBrowser) 
            {
                if (HideWhenApplicationHasNoElevatedPrivileges)
                {
                    if (!Application.Current.HasElevatedPermissions)
                    {
                        FrameworkElement _element;
                        _element = this.AssociatedObject as FrameworkElement;
                        _element.Visibility = Visibility.Collapsed;
                    }
                }
            }
            else
            {
                FrameworkElement _element;
                _element = this.AssociatedObject as FrameworkElement;
                _element.Visibility = Visibility.Collapsed;
            }
            base.OnAttached();
        }

        protected override void Invoke(object o)
        {
            Application.Current.MainWindow.Close();
        }

        public bool HideWhenApplicationHasNoElevatedPrivileges
        {
            get { return (bool)GetValue(HideWhenApplicationHasNoElevatedPrivilegesProperty); }
            set { SetValue(HideWhenApplicationHasNoElevatedPrivilegesProperty, value); }
        }

        public static readonly DependencyProperty HideWhenApplicationHasNoElevatedPrivilegesProperty =
            DependencyProperty.Register(
                "HideWhenApplicationHasNoElevatedPrivileges", 
                typeof(bool), 
                typeof(CloseAppBehavior), 
                new PropertyMetadata(true));

        
    }
}
